package com.hy.ruiji.service.serviceImpl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hy.ruiji.common.R;
import com.hy.ruiji.common.Status;
import com.hy.ruiji.enyity.Employee;
import com.hy.ruiji.mapper.EmployeeMapper;
import com.hy.ruiji.service.EmployeeService;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;

@Service
public class EmployeeServiceImpl extends ServiceImpl<EmployeeMapper,Employee> implements EmployeeService {

    /**
     * 员工登录
     * @param employee 前端传过来的json参数
     * @return 返回结果实体类
     */
    @Override
    public R<Employee> login( Employee employee) {
        //1、对页面提交的名文密码进行一个加密处理
        String password = employee.getPassword();
        password=DigestUtils.md5DigestAsHex(password.getBytes());
        //2、对数据库名字进行匹配
        LambdaQueryWrapper<Employee> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Employee::getUsername,employee.getUsername());
        Employee employee1 = this.getOne(wrapper);
        //3、未查询到返回结果失败
        if(employee1==null){
            return R.error("未找到该用户");
        }
        //4、比对密码判断是否相同
        else if (!employee1.getPassword().equals(password)) {
            return R.error("密码错误，请从新输入");
        }
        //5、查看员工状态
        if(employee1.getStatus()== Status.NOT_PASS){
            return R.error("用户状态异常");
        }
        return R.success(employee1);
    }
    @Override
    public R<String> saveEmployee(HttpServletRequest request, Employee employee) {
        //获得创建人的id
        //Long empId =(Long)request.getSession().getAttribute(Status.SESSION_USER);
        //设置初始密码并且进行名文加密
        employee.setPassword(DigestUtils.md5DigestAsHex(Status.PRE_PASSWORD.getBytes()));
        //对时间进行初始化
        //employee.setCreateTime(LocalDateTime.now());
        //employee.setUpdateTime(LocalDateTime.now());
        //添加创建人的id
        //employee.setCreateUser(empId);
        //employee.setUpdateUser(empId);
        this.save(employee);
        return R.success("添加成功！");
    }
}
